Scroll Progress Bar

Type Casting

Type casting, also known as type conversion, is a way to convert a variable from one data type to another. In C, type casting is used to ensure compatibility between different data types during expressions or assignments. Sometimes, the data type of an expression needs to be explicitly converted to the desired type to avoid data loss or perform specific operations.

Usage and Syntax:

To perform type casting in C, use the desired data type enclosed in parentheses before the expression or variable that want to convert.

data_type new_variable = (data_type) old_variable;
Sample Code with Explanation and Output:

#include <stdio.h>

int main() {
    int num1 = 10;
    int num2 = 3;
    float result;

    // Performing type casting to get the floating-point division result
    result = (float)num1 / num2;

    printf("Floating-point division result: %f\n", result);

    // Type casting to get the integer division result (truncates decimal part)
    int integerResult = (int)(num1 / num2);

    printf("Integer division result: %d\n", integerResult);

    return 0;
}

Output:

Floating-point division result: 3.333333
Integer division result: 3
Explanation:
  • In the sample code, have two integer variables num1 and num2 with values 10 and 3, respectively.
  • To obtain the floating-point division result (with decimal part), perform type casting by converting num1 to a float before dividing it by num2.
  • The result of num1 / num2 without type casting would be 3, but with type casting, it becomes 3.333333.
  • Print the floating-point division result using %f format specifier.
  • To obtain the integer division result (without decimal part), perform type casting by converting the result of num1 / num2 to an integer.
  • The result is 3, and print it using %d format specifier.

Note: Type casting is important when dealing with expressions involving mixed data types. It helps to avoid unexpected behaviour and ensure correct results. However, be cautious while performing type casting, as it may lead to data loss if the converted value is outside the range of the target data type.


What is type casting in C?


Conversion

What is an implicit type cast in C?


Automatic

What is an explicit type cast in C?


Casting